package com.ruoyi.test.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 1. 给定一个区间集合，合并有重叠的区间。例如：
 *          给定 [1,3],[2,6],[8,10],[15,18],
 *          返回 [1,6],[8,10],[15,18]
 */

    class Interval {
        int start;
        int end;

        Interval(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public String toString() {
            return "[" + start + "," + end + "]";
        }
    }


public class compareArray {
        public static List<Interval> merge(List<Interval> intervals) {
            if (intervals == null || intervals.size() <= 1) {
                return intervals;
            }

            // 按照区间的开始位置排序
            intervals.sort((a, b) -> a.start - b.start);

            List<Interval> result = new ArrayList<>();
            Interval current = intervals.get(0);
            result.add(current);

            for (Interval interval : intervals) {
                if (interval.start <= current.end) { // 有重叠
                    current.end = Math.max(current.end, interval.end); // 合并区间
                } else { // 没有重叠
                    current = interval;
                    result.add(current);
                }
            }

            return result;
        }

        public static void main(String[] args) {
            List<Interval> intervals = Arrays.asList(
                    new Interval(1, 3),
                    new Interval(2, 6),
                    new Interval(8, 10),
                    new Interval(15, 18)
            );

            List<Interval> merged = merge1(intervals);
            System.out.println("Merged Intervals: " + merged);
        }

        public static List<Interval> merge1(List<Interval> intervals){

            intervals.sort((a,b)->a.start-b.start);
            Interval interval = intervals.get(0);
            List<Interval> result = new ArrayList<>();
            int compareEnd = interval.end;
            for(Interval interval1:intervals){
                if(interval1.start > compareEnd){
                    compareEnd = interval1.start;
                }else {
                    result.add(new Interval(interval1.start,compareEnd));
                }
            }
            return result;

        }
}
